<?php

namespace app\util;

use think\Db;
use think\Model;

/*
 * 企业微信
 * 开发文档 https://work.weixin.qq.com/api/doc/90000/90135/90664
 */

class QyWx extends Model {
    
//    const CORPID = 'ww824514a1159f021f';
//    const CORPSECRET = 'Hkg3nRudceodCmZt10QFqkrk-EdR2LThdNr3MfM4HFc';
//    const AgentId = 1000005;
    
    const CORPID = 'wwfefbcd6b274241ef';
    const CORPSECRET = 'VfQOCSuBPFUISjYE-7VrxLC_L70qGiADHQ2d5wIc8-0';
    const AgentId = 1000003;

    function __construct() {
        parent::__construct();
    }

    //获取access_token
    public function accessToken() {
        //$access_token = $this->redis->get("weixin_access_token"); //存入redis，这里要结合自己的项目，对redis或者memcahe进行设置
        $access_token = FALSE;
        if (!$access_token) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".self::CORPID."&corpsecret=".  self::CORPSECRET;
            $data = json_decode($this->httpGet($url), true);
            if (isset($data['access_token']) && $data['access_token'] != '') {
                //$access_token = $this->redis->set("weixin_access_token", $data['access_token'], 7200);
                $access_token = $data['access_token'];
            } else {
                return false;
            }
        }
        return $access_token;
    }
    
    /**
     * 发送消息
     * 文档https://work.weixin.qq.com/api/doc/90000/90135/90236
     */
    public function sendSMS($touser, $content)
    {
        $access_token = $this->accessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?debug=1&access_token=".$access_token;
        //创蓝接口参数
        $postArr = array(
            'touser' => $touser,//指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为”@all”，则向该企业应用的全部成员发送
            'msgtype' => 'text',
            'agentid' => self::AgentId,//企业应用的id，整型
            'text' => ['content'=>$content],//urlencode($msg)
            'safe' => 0,//表示是否是保密消息，0表示可对外分享，1表示不能分享且内容显示水印，默认为0
        );
        $result = $this->curlPost($url, $postArr);
        return $result;
    }
    
    //远程请求，可以调用自己项目的远程请求

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    
    /**
     * 通过CURL发送HTTP请求
     * @param string $url //请求URL
     * @param array $postFields //请求参数
     * @return mixed
     */
    private function curlPost($url, $postFields)
    {
        $postFields = json_encode($postFields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
            ]
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($ch);
        if (false == $ret) {
            $result = curl_error($ch);
        } else {
            $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 " . $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close($ch);
        return $result;
    }

    

}
